<template>
  <el-dialog
      v-model="dialogVisible"
      :before-close="handleClose"
      title="编辑库存"
      width="400px"
  >
    <div v-if="product" class="stock-edit-form">
      <!-- 商品信息 -->
      <div class="product-info">
        <img
            v-if="product.mainImage"
            :src="product.mainImage"
            alt="商品图片"
            class="product-image"
        />
        <div class="product-details">
          <h4>{{ product.name }}</h4>
          <p class="current-stock">当前库存：{{ product.stock }}</p>
        </div>
      </div>

      <!-- 库存编辑表单 -->
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="80px"
          @submit.prevent
      >
        <el-form-item label="新库存" prop="stock">
          <el-input-number
              v-model="form.stock"
              :max="999999"
              :min="0"
              :precision="0"
              controls-position="right"
              placeholder="请输入新的库存数量"
              style="width: 100%"
          >
            <template #suffix>
              <span class="unit-text">件</span>
            </template>
          </el-input-number>
        </el-form-item>

        <div class="stock-info">
          <div class="info-item">
            <span class="label">当前库存：</span>
            <span class="value">{{ product?.stock || 0 }} 件</span>
          </div>
          <div class="info-item">
            <span class="label">变更数量：</span>
            <span :class="['value', stockChangeClass]">
              {{ stockChangeText }}
            </span>
          </div>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            :loading="loading"
            type="primary"
            @click="handleSubmit"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, nextTick, reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {useProductStore} from '@/store/product'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  product: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

// Store
const productStore = useProductStore()

// 响应式数据
const formRef = ref()
const loading = ref(false)

const form = reactive({
  stock: 0
})

// 表单验证规则
const rules = {
  stock: [
    {required: true, message: '请输入库存数量', trigger: 'blur'},
    {type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur'}
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 库存变更计算
const stockChange = computed(() => {
  const currentStock = props.product?.stock || 0
  return form.stock - currentStock
})

const stockChangeText = computed(() => {
  const change = stockChange.value
  if (change === 0) return '无变更'
  return change > 0 ? `+${change} 件` : `${change} 件`
})

const stockChangeClass = computed(() => {
  const change = stockChange.value
  if (change === 0) return 'neutral'
  return change > 0 ? 'increase' : 'decrease'
})

// 方法
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    loading.value = true

    await productStore.updateProductStock(props.product.id, form.stock)

    ElMessage.success('库存更新成功')
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('更新库存失败:', error)
      ElMessage.error('更新失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    stock: 0
  })
}

const initForm = () => {
  if (props.product) {
    form.stock = props.product.stock
  }
}

// 监听器
watch(
    () => props.product,
    (newProduct) => {
      if (newProduct && props.modelValue) {
        nextTick(() => {
          initForm()
        })
      }
    },
    {immediate: true}
)

watch(
    () => props.modelValue,
    (newValue) => {
      if (newValue && props.product) {
        nextTick(() => {
          initForm()
        })
      } else if (!newValue) {
        resetForm()
      }
    }
)
</script>

<style scoped>
.stock-edit-form {
  padding: 10px 0;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #ddd;
}

.product-details h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #303133;
}

.current-stock {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

.stock-info {
  margin: 16px 0;
  padding: 12px;
  background: var(--admin-bg-secondary);
  border-radius: var(--admin-radius-md);
  border: 1px solid var(--admin-border-light);
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 13px;
  color: var(--admin-text-secondary);
  font-weight: 500;
}

.value {
  font-size: 13px;
  font-weight: 600;
}

.value.neutral {
  color: var(--admin-text-tertiary);
}

.value.increase {
  color: var(--admin-success);
}

.value.decrease {
  color: var(--admin-error);
}

.unit-text {
  color: var(--admin-text-tertiary);
  font-size: 12px;
  margin-right: 8px;
}
</style>
